package com.salary.snippet

import scala.xml.{NodeSeq,Text}
import net.liftweb.http.{RequestVar,S,SHtml}
import net.liftweb.common.Full
import net.liftweb.util.Helpers.{bind,chooseTemplate}
import net.liftweb.util.Helpers._
import net.liftweb.mapper._

import model.Employee

class Employees {
	val sex_val = List("man", "woman").map(xx => (xx, xx))
	def show (xhtml : NodeSeq) : NodeSeq = {
		val em:List[Employee] = Employee.findAll
		em.flatMap({item => 
				bind("emp", chooseTemplate("emlist", "entry", xhtml),
				"id" -> Text(item.idx),
				"name" -> Text(item.em_name),
				"sex" -> Text(item.sex),
				"nationality" -> Text(item.nationality.toString),
				"salary" -> Text(item.salary.toString),
				"startdate" -> Text(item.startdate.toString),
                "actions" -> { SHtml.link("/viewEmployee", () => item.delete_!, Text("Delete")) ++ Text(" ") ++
                               SHtml.link("/editEmployee", () => currentEmployeeVar(item), Text("Edit")) })
			})

	}

	object currentEmployeeVar extends RequestVar[Employee]({
		Employee.create
	})
	def currentEmployee = currentEmployeeVar.is

	def buildEntry(xhtml : NodeSeq, item: Employee) : NodeSeq = {
		println("build: " + item.startdate)
		bind("entry", chooseTemplate("emp", "empEntry", xhtml),
			"id" -> SHtml.text(item.idx, item.idx(_)),
			"name" -> SHtml.text(item.em_name, item.em_name(_)),
			"sex" -> SHtml.select(sex_val, Full("man"), item.sex(_)),
			"nationality" -> item.nationality._toForm,
			"salary" -> SHtml.text(item.salary.toString, v => item.salary(v.toInt)),
			"startdate" -%> SHtml.text(item.startdate.toString, v => item.startdate.setFromAny(v) )% ("size" -> "10"))
	}
	
	def add(xhtml : NodeSeq) : NodeSeq = {
		val item = Employee.create
		def doAdd () { 
			item.save
 		    S.redirectTo("/viewEmployee")
		}

		bind("emp", xhtml,
			 "table" -> buildEntry(xhtml, item),
			 "submit" -> SHtml.submit("Add", doAdd))
	}
	
	def edit(xhtml : NodeSeq) : NodeSeq = {

		def doSave () = {
		  currentEmployee.validate match {
			case Nil =>
			  currentEmployeeVar.save
			  S.redirectTo("/viewEmployee")
			case x => S.error(x)
		  }
		}

		val item = currentEmployee

		bind("emp", xhtml,
			 "key" -> SHtml.hidden(() => currentEmployeeVar(item)),
			 "table" -> buildEntry(xhtml, item),
			 "submit" -> SHtml.submit("Save", doSave))
	}
}

